package edu.pw.elka.gtsna.graph_algorithms;

import java.util.LinkedHashSet;
import java.util.Set;

import edu.pw.elka.gtsna.graph.Graph;

public class FindComponents {
	
	Graph graph;
	
	CheckConnectivity connectivity;
	Set<Set<Integer>> components;
	
	int checked[];
	
	public FindComponents(Graph graph) {
		super();
		this.graph = graph;
		connectivity = new CheckConnectivity(graph);
		checked = new int[graph.getNumOfNodes()+1];
		components = new LinkedHashSet<Set<Integer>>();
	}
	
	
	
	public Set<Set<Integer>> getComponents() {
		return components;
	}



	public void setSubgraph(Set<Integer> subgraph) {
		components.clear();
	}

	public Set<Integer> getIntersection(){
		
		for (int i=1; i<graph.getNumOfNodes()+1;i++){
			checked[i] = 0;
		}
		
		Set<Integer> inter = new LinkedHashSet<Integer>();
		for (Set<Integer> com : components){
			for(int n: graph.getNeigbours(com)){
				checked[n]++;
			}
		}
		
		for (int i=1; i<graph.getNumOfNodes()+1;i++){
			if (checked[i] == size()){
				inter.add(i);
			}
		}
		
		return inter;
	}
	


	public int size(){
		return components.size();
	}
	
	public void compute(){
		components.clear();
		
		Set<Integer> subgraph2 = new LinkedHashSet<Integer>(graph.getAllNodes());
		
		connectivity.check(subgraph2);
		components.add(connectivity.getComponent());
		
		while(!connectivity.isConencted()){
			subgraph2.removeAll(connectivity.getComponent());
			connectivity.check(subgraph2);
			components.add(connectivity.getComponent());
		}			
	}
	
}
